function checkValue(obj) {
	var value = $(obj).val(); //.attr('value');
	if(value != '' && !checkEnName(value)) {
		$(obj).addClass('warning');
	}
}

function rmError(obj) {
	$(obj).removeClass('warning');
}

$(document)
	.on('click', '._request_head_del', function() {
		var that = $(this);
		that.parent().parent('._raw_request_head').remove();
	})

.on('click', '._response_head_del', function() {
	var that = $(this);
	that.parent().parent('._raw_response_head').remove();
})

//把请求参数写入页面
function request_head(jsondata) {

	if(jsondata == '' || jsondata == null) {

		var user = Object();
		user['name'] = '';
		user['value'] = '';
		jPut.jput_format_request.append(user);
		return;
	}

	var data = JSON.parse(jsondata);
	for(var a in data) {
		var user = Object();
		user['name'] = data[a].name;
		user['value'] = data[a].value;
		jPut.jput_format_request.append(user);
	}
	var user = Object();
	user['name'] = '';
	user['value'] = '';
	jPut.jput_format_request.append(user);
}

function response_head(jsondata) {

	if(jsondata == '' || jsondata == null) {

		var user = Object();
		user['name'] = '';
		user['value'] = '';
		jPut.jput_format_response.append(user);
		return;
	}

	var data = JSON.parse(jsondata);
	for(var a in data) {
		var user = Object();
		user['name'] = data[a].name;
		user['value'] = data[a].value;
		jPut.jput_format_response.append(user);
	}
	var user = Object();
	user['name'] = '';
	user['value'] = '';
	jPut.jput_format_response.append(user);
}

$(function() {
	$("._blur_num_rz").blur(function() {
		var timeout = $("._blur_num_rz").val();
		if(stringIsNull(timeout)) {
			add_auth_error('service_timeout', '请输入服务超时时间');
			return;
		}
		//不为空的时候，需要判断是否为数字
		if(!checkNum(timeout)) {
			add_auth_error('service_timeout', '请输入正确的服务超时时间');
		}
	});

	$("._blur_num_rz").focus(function() {
		rm_auth_error('service_timeout');
	});

	//点击“确定”按钮
	$('._add_confirm').click(function() {
		var data = getServiceData();
		if(!data) {
			return;
		}

		function run_waitMe(register) {
			$('#register').waitMe({
				effect: 'ios',
				bg: 'rgba(16,128,242,0)',
				text: '提交中...',
				color: '#fff',
				padding: '10px',
				sizeW: '',
				sizeH: '',
				source: 'img.svg'
			});
		}

		var cur = $(this);
		// 按钮置为不可点击
		it_enable(cur, true);
		$('#register').text('');
		run_waitMe('register');

		//二级分类id
		data.tid = $('#select-crumbs2').children('input[name="select-crumbs2"]').val()
			//ajax请求
		$.ajax({
			url: '/apiworks/serviceEdit.html',
			type: 'POST',
			dataType: 'json',
			async: true,
			data: data,
			success: function(req) {
				it_enable(cur, false);
				$('#register').waitMe('hide');
				$('#register').text('确定');
				if(req.status == 200) {
					show_msg({
						msg: '操作成功',
						type: 'ok',
						time: 1500
					});
					//return
					//location.reload();
					location.href = "/apiworks/servicelist.html";
				} else {
					if(req.status == 1) {
						add_auth_error(req.data, req.msg)
					} else {
						show_msg({
							msg: req.msg,
							type: 'error',
							time: 2000
						});
					}

				}
			},
			error: function() {
				it_enable(cur, false);
				$('#register').waitMe('hide');
				$('#register').text('确定');
				show_msg({
					msg: '系统异常',
					type: 'error',
					time: 1000
				});
			}
		});

	});

	//request headers 追加
	$('._add_request_headers').click(function() {
		var user1 = Object();
		user1['name'] = '';
		user1['value'] = '';
		jPut.jput_format_request.append(user1);
	});

	$("#dlanxhover").click(function() {
		$(this).parent().toggleClass("");
		$(this).parent().prevAll("#dlanxhout").removeClass("bg")
		$(this).parent().nextAll("#dlanxhout").removeClass("bg")
		$(this).parent().next().slideToggle();
		$(this).parent().prevAll("#dlanxhover").slideUp("slow");
		$(this).parent().next().nextAll("#dlanxhover").slideUp("slow");
		//return false;
	});

	//response headers 追加
	$('._add_response_headers').click(function() {
		//defining new user
		var user2 = Object();
		//appening to jput variable
		user2['name'] = '';
		user2['value'] = '';
		jPut.jput_format_response.append(user2);
	});

	//下拉列表
	var seLevelObj = JSON.parse($('._categoryObj').val())
		//console.log(seLevelObj)
	function newObj(obj) {
		var newObj = {}
		for(var key in obj) {
			var newkey = key.split('-')[1]
			newObj[newkey] = obj[key]
		}
		return newObj
	}
	var newseLevelObj = newObj(seLevelObj)
		//选中的一级分类Id
	var selectedFirstId = $('._firstCateId').val()
		//选中的二级分类id
	var selectedSecondId = $('._secCateId').val()
		//第一个下拉栏
		//console.log(!newseLevelObj[selectedFirstId])
	if(newseLevelObj[selectedFirstId]) {
		for(var firstList in seLevelObj) {
			// 一级分类		
			if(seLevelObj[firstList].id != selectedFirstId) {
				$('._selecte_category_list:eq(0)').append('<option value=' + seLevelObj[firstList].id + '>' + seLevelObj[firstList].name + '</option>')
			} else if(seLevelObj[firstList].id == selectedFirstId) {
				$('._selecte_category_list:eq(0)').append('<option selected="selected" value=' + seLevelObj[firstList].id + '>' + seLevelObj[firstList].name + '</option>')
			}
		}
	} else {
		$('._selecte_category_list:eq(0)').append('<option selected="selected" value="0">选择分类</option>')
		for(var firstList in seLevelObj) {
			$('._selecte_category_list:eq(0)').append('<option value=' + seLevelObj[firstList].id + '>' + seLevelObj[firstList].name + '</option>')
		}	
	}

	//第二个下拉栏
	if(selectedSecondId != '0' && selectedSecondId != ' ') {
		if(newseLevelObj[selectedFirstId]) {
			for(var secondList in newseLevelObj[selectedFirstId].children) {
				if(secondList != selectedSecondId) {
					$('._selecte_category_list:eq(1)').append('<option value=' + secondList + '>' + newseLevelObj[selectedFirstId].children[secondList].name + '</option>')
				} else {
					$('._selecte_category_list:eq(1)').append('<option selected="selected" value=' + secondList + '>' + newseLevelObj[selectedFirstId].children[secondList].name + '</option>')
				}
			}
		} else {
			$('._selecte_category_list:eq(1)').append('<option value = "0">暂无分类</option>')
		}
	} else {
		$('._selecte_category_list:eq(1)').append('<option value = "0">暂无分类</option>')
	}
	$('._selecte_category_list:eq(0)').selectlist({
		zIndex: 10,
		width: 200,
		height: 40,
		onChange: function() {
			$('#select-crumbs2').remove()
			if(newseLevelObj[$('#selected_category .selected').attr('data-value')]){
				var childObj = newseLevelObj[$('#selected_category .selected').attr('data-value')].children
			}else{
				var childObj = 0
			}
			var htmlArr = ['<select id="select-crumbs2" class="class _selecte_category_list fl">']
			if(childObj) {
				for(var child in childObj) {
					htmlArr.push('<option value=' + child + '>' + childObj[child].name + '</option>')
				}
			} else {
				htmlArr.push('<option value="0">暂无分类</option>')
			}
			htmlArr.push('</select>')
			$('._secList').html(htmlArr.join(''))
			$('._selecte_category_list:eq(1)').selectlist({
				zIndex: 10,
				width: 200,
				height: 40
			});
		}
	});
	//初次显示二级分类
	$('._selecte_category_list:eq(1)').selectlist({
		zIndex: 10,
		width: 200,
		height: 40
	});

});

//获取二维数组值及转json数据格式
function getApiRequestParam(dom_name, params, params_num) {
	var api_request_param = $("input[name^='" + dom_name + "']");
	//console.log(api_request_param);
	var json_params = new Array();

	var array_num = Math.floor(api_request_param.length / params_num);
	for(var j = 0; j < array_num; j++) {
		//json_params[j] = new Array();
		json_params[j] = new Object();
	}

	for(var i = 0; i < api_request_param.length; i++) {
		var num = i % params_num;
		var key = Math.floor(i / params_num);
		json_params[key][params[num]] = api_request_param[i].value;
	}
	return JSON.stringify(json_params);
}

function getServiceData() {
	var service_id = $('._service_id').val();
	var service_name = $("._service_name").val();
	var service_name_en = $("._service_name_en").val();
	var service_introduction = $("._service_introduction").val();
	var service_logo = $("._service_logo").val();
	var service_timeout = $("._service_timeout").val();
	var service_host = $('._service_host').val();
	var service_request_heads = JSON.parse(getApiRequestParam('request', ['name', 'value'], 2));
	var service_response_heads = JSON.parse(getApiRequestParam('response', ['name', 'value'], 2));
	var category_id = $('#selected_category').children('input[name="selected_category"]').val();
	//console.log(category_id)
	//TODO if(category_id == 0||category_id == '') {
	if(category_id == '') {
		$("#selected_category").addClass('warning');
		$("#selected_category_id").show();
		return;
	}
	//参数为空判断
	batchVer('_blur_rz');
	//有错误样式不允许提交
	if(haserror('_blur_rz')) {
		return;
	}

	var cur = $(this);
	// 按钮置为不可点击
	it_enable(cur, true);
	//设置发送的数据
	var data = {};
	data.service_id = service_id;
	data.service_name = service_name;
	data.service_name_en = service_name_en;
	data.service_introduction = service_introduction;
	data.service_logo = service_logo;
	data.service_timeout = service_timeout;
	data.service_host = service_host;
	data.service_request_heads = service_request_heads;
	data.service_response_heads = service_response_heads;
	data.service_proto = $("input[name='service_proto']:checked").val();
	data.category_id = category_id;

	return data;

}